const os = require('os');
const logger = require('./logger')
const net = require('net');
const colors = require('colors');


// 检查端口是否被占用
function isPortFree(port) {
    return new Promise((resolve) => {
        const server = net.createServer()
            .once('error', () => resolve(false)) // 端口被占用
            .once('listening', () => {
                server.close();
                resolve(true); // 端口可用
            })
            .listen(port);
    });
}

function getMac() {
    let mac = ''

    const networkInterfaces = os.networkInterfaces()

    for (const i in networkInterfaces) {
        for (const j in networkInterfaces[i]) {
            if (
                networkInterfaces[i][j]['family'] === 'IPv4' &&
                networkInterfaces[i][j]['mac'] !== '00:00:00:00:00:00' &&
                networkInterfaces[i][j]['address'] !== '127.0.0.1'
            ) {
                mac = networkInterfaces[i][j]['mac']
            }
        }
    }

    logger.info(`调用src/background/utils/network.js获取mac地址：〖${mac}〗`)
    return mac
}

// 获取本机 IP 地址
function getLocalIP() {
    let localIP = '0.0.0.0';

    const interfaces = os.networkInterfaces();

    for (const name of Object.keys(interfaces)) {
        for (const iface of interfaces[name]) {
            if (iface.family === 'IPv4' && !iface.internal) {
                localIP = iface.address;
            }
        }
    }

    console.log(`[+10016]via utils/network.js get localIP ::〖${localIP}〗`.cyan);

    return localIP; // 如果没有找到 IP，返回默认值
}

module.exports = {
    getMac,
    getLocalIP,
    isPortFree,
}